package com.campus.merchant.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.merchant.bean.goodsCategory.GoodsCategorySaveBean;
import com.campus.merchant.bean.goodsCategory.GoodsCategoryUpdateBean;
import com.campus.merchant.entity.GoodsCategory;
import com.campus.merchant.mapper.GoodsCategoryMapper;
import com.campus.merchant.vo.goodsCategory.GoodsCategoryVO;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品分类表 服务实现类
 * </p>
 *
 * @author ZhaoYuJie
 * @since 2025-04-18
 */
@Service
public class GoodsCategoryService extends ServiceImpl<GoodsCategoryMapper, GoodsCategory> {

    public List<GoodsCategoryVO> getCategoriesByMerchantId(Integer merchantId) {
        List<GoodsCategory> goodsCategories = baseMapper.selectList(Wrappers.lambdaQuery(GoodsCategory.class)
                .eq(GoodsCategory::getMerchantId, merchantId)
                .eq(GoodsCategory::getStatus, 1)
                .orderByAsc(GoodsCategory::getSort));
        if(CollectionUtil.isNotEmpty(goodsCategories)){
            List<GoodsCategoryVO> goodsCategoryVOList = goodsCategories.stream().map(category -> {
                GoodsCategoryVO vo = new GoodsCategoryVO();
                BeanUtil.copyProperties(category, vo);
                return vo;
            }).collect(Collectors.toList());
            return goodsCategoryVOList;
        }
        return Collections.emptyList();
    }

    public Integer saveCategory(GoodsCategorySaveBean bean) {
        GoodsCategory category = new GoodsCategory();
        BeanUtil.copyProperties(bean, category);
        category.setStatus(1);
        baseMapper.insert(category);
        return category.getId();
    }

    public void updateCategory(GoodsCategoryUpdateBean bean) {
        GoodsCategory category = new GoodsCategory();
        BeanUtil.copyProperties(bean, category);
        baseMapper.updateById(category);
    }

    public GoodsCategoryVO getCategoryDetail(Integer id) {
        GoodsCategory category = baseMapper.selectById(id);
        if(category != null){
            GoodsCategoryVO vo = new GoodsCategoryVO();
            BeanUtil.copyProperties(category, vo);
            return vo;
        }
        return null;
    }

    public void deleteCategory(Integer id) {
        baseMapper.deleteById(id);
    }
}
